<?php
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use app\common\model\AdminLog as DataMode;
/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle{
    private $code;
    private $message;
    private $statuscode;
    /**
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response    {
        $this->statuscode = $this->code = 500;
        if($e instanceof BaseException){//是否异常实例
            $this->code = $e->code;
            $this->message = $e->message;
        }else{
            if (config('app_debug')){
                return parent::render($request, $e); // TODO: Change the autogenerated stub
            }
            $this->code = 500;
            $this->message = $e->getMessage() ?: '服务器内部错误';
        }
        // Http异常
        if ($e instanceof \think\exception\HttpException)        {
            $this->statuscode = $this->code = $e->getStatusCode();
        }
        $data = [
            'code' => $this->statuscode,
            'msg' => $this->message,
            'time' => date('Y-m-d H:i:s',time()),
            'data' => ['url'=>$request->url()],
        ];
        $app = strtolower(app('http')->getName());
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $url = strtolower($request->url());
        if (!empty($app) && !empty($controller) && !empty($action)) {
            $updata = [
                'id'=>GetSnowID(),
                'type' => 7,
                'module' => $app,
                'controller' => $controller,
                'action' => $action,
                'method' => $request->method(),
                'url' => $url,
                'post_data' => json_encode($request->post(), JSON_UNESCAPED_UNICODE),
                'get_data' => json_encode($request->get(), JSON_UNESCAPED_UNICODE),
                'headers' => json_encode($request->header(), JSON_UNESCAPED_UNICODE),
                'agent' => $request->server('HTTP_USER_AGENT'),
                'ip' => $request->ip(),
                'content' => $this->message,
                'create_time' => date('Y-m-d H:i:s'),
                'create_id' => GetToken('id') ?: 0,
            ];
            $Model = new DataMode();
            $Model->insert($updata);
        }

        if ($request->isAjax() || $request->isPost()) {
            return json($data,$this->statuscode);
        }
        return parent::render($request, $e);

    }
}